import re

from wtforms import StringField, TextAreaField, widgets, DecimalField, IntegerField, SelectField, SelectMultipleField, \
    FileField, PasswordField
from flask_wtf import FlaskForm
from wtforms.validators import Length, DataRequired, NumberRange, ValidationError, EqualTo, Email
# from flask_wtf.file import FileAllowed
from apps.models import Publish, Author, User


class PublishForm(FlaskForm):
    name = StringField(
        label='出版社名称',
        validators=[
            DataRequired(message='请输入出版社名称'),
            Length(min=2, max=32, message='长度在2-32个字符之间')
        ],
        render_kw={
            'class': 'form-control',
            'placeholder': '请输入出版社名称'
        }
    )
    address = StringField(
        label='出版社地址',
        validators=[
            DataRequired(message='请输入出版社地址'),
            Length(min=2, max=100, message='长度在2-100个字符之间')
        ],
        render_kw={
            'class': 'form-control',
            'placeholder': '请输入出版社地址'
        }
    )
    intro = TextAreaField(
        label='出版社简介',
        validators=[
            DataRequired(message='请输入出版社简介'),
            Length(max=500, message='长度在0-500个字符之间')
        ],
        render_kw={
            'class': 'form-control',
            'placeholder': '请输入出版社简介',
            'rows': 5,
            'cols': 50
        }
    )


class AuthorForm(FlaskForm):
    name = StringField(
        label='作者名称',
        validators=[
            DataRequired(message='请输入作者名称'),
            Length(min=2, max=32, message='长度在2-32个字符之间')
        ],
        render_kw={
            'class': 'form-control',
            'placeholder': '请输入作者名称',
            'required': False
        }
    )
    age = IntegerField(
        label='作者年龄',
        validators=[
            DataRequired(message='请输入作者年龄'),
            NumberRange(min=1, max=100, message='年龄在1-120岁之间')
        ],
        render_kw={
            'class': 'form-control',
            'placeholder': '请输入作者年龄'
        }
    )
    mobile = StringField(
        label='作者手机号',
        validators=[
            DataRequired(message='请输入作者手机号'),
            Length(min=11, max=11, message='手机号长度为11位')
        ],
        render_kw={
            'class': 'form-control',
            'placeholder': '请输入作者手机号',
            'required': False
        }
    )
    address = StringField(
        label='作者地址',
        validators=[
            DataRequired(message='请输入作者地址'),
            Length(min=2, max=100, message='长度在2-100个字符之间')
        ],
        render_kw={
            'class': 'form-control',
            'placeholder': '请输入作者地址'
        }
    )
    intro = TextAreaField(
        label='作者简介',
        validators=[
            Length(max=500, message='长度在0-500个字符之间')
        ],
        render_kw={
            'class': 'form-control',
            'placeholder': '请输入作者简介',
            'rows': 5,
            'cols': 50
        }
    )

    def validate_mobile(self, field):
        mobile = field.data
        mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
        if not mobile_re.match(mobile):
            raise ValidationError('手机号格式不正确')


class BookForm(FlaskForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 在表单实例化时加载选项
        self.publish.choices = [('0', '请选择出版社')]+ [(p.p_id, p.name) for p in Publish.query.all()]
        self.author.choices = [('0', '请选择作者')] + [(a.a_id, a.name) for a in Author.query.all()]

        # 如果没有设置默认值且有选项，则默认选择第一个出版社
        # if not self.publish.data and self.publish.choices:
        #     self.publish.data = self.publish.choices[0][0]
        #
        # # 如果没有设置默认值且有选项，则默认选择第一个作者
        # if not self.author.data and len(self.author.choices) > 1:
        #     self.author.data = [self.author.choices[1][0]]  # 选择第一个有效作者（跳过"请选择作者"）

    name = StringField(
        label='图书名称',
        validators=[
            DataRequired(message='请输入图书名称'),
            Length(min=2, max=32, message='长度在2-32个字符之间')
        ],
        render_kw={
            'class': 'form-control',
            'placeholder': '请输入图书名称'
        }
    )
    isbn = StringField(
        label='图书ISBN',
        validators=[
            DataRequired(message='请输入图书ISBN'),
            Length(min=2, max=32, message='长度在2-32个字符之间')
        ],
        render_kw={
            'class': 'form-control',
            'placeholder': '请输入图书ISBN'
        }
    )
    photo = FileField(
        label='图书图片',
        render_kw={
            'class': 'custom-file-input',
            'placeholder': '请输入图书图片'
        }
    )
    price = DecimalField(label='图书价格',
                         validators=[DataRequired(message='请输入图书价格')],
                         render_kw={
                             'class': 'form-control',
                             'placeholder': '请输入图书价格'
                         }
                         )
    publish = SelectField(label='图书出版社',
                          coerce=int,
                          choices=[],
                          validators=[DataRequired(message='请选择图书出版社')],
                          render_kw={
                              'class': 'form-control  custom-select'
                          })
    author = SelectMultipleField(label='图书作者',
                                 coerce=int,
                                 choices=[],
                                 validators=[DataRequired(message='请选择图书作者')],
                                 render_kw={
                                     'class': 'form-control  custom-select', 'placeholder': "请选择作者",
                                     'multiple': 'multiple'
                                 })


class LoginForm(FlaskForm):
    username = StringField(validators=[DataRequired(message='请输入用户名'), Length(min=2, max=100, message='长度在2-10个字符之间')])
    password = PasswordField(validators=[DataRequired(message='请输入密码'), Length(min=2, max=10,message='长度在2-10个字符之间')])

    def validate_username(self, field):
        username = field.data
        user = User.query.filter_by(username=username).first()
        if not user:
            raise ValidationError('用户未注册')


class RegisterForm(FlaskForm):
    username = StringField(
        validators=[DataRequired(message='请输入用户名'), Length(min=2, max=100, message='长度在2-10个字符之间')],render_kw={'class': 'form-control','placeholder': '请输入用户名'})
    password = PasswordField(
        validators=[DataRequired(message='请输入密码'), Length(min=2, max=10, message='长度在2-10个字符之间')],render_kw={'class': 'form-control','placeholder': '请输入密码'})
    v_password = PasswordField(validators=[EqualTo('password', message='密码不一致')],render_kw={'class': 'form-control','placeholder': '请输入确认密码'})
    email = StringField(validators=[Email(message='邮箱格式不正确')],render_kw={'class': 'form-control', 'placeholder': '请输入邮箱'})

    def validate_username(self, field):
        username = field.data
        user = User.query.filter_by(username=username).first()
        if user:
            raise ValidationError('用户已存在')
